<template>
  <a-modal
    :title="title"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="_submit"
    @cancel="_cancel">
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="false" label="主键ID">
          <a-input v-decorator="['bannerId', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-form-item label="图片">
          <a-upload
            name="banner"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :before-upload="beforeUpload"
            :customRequest="customRequest"
            @change="handleChange"
            v-decorator="['bannerPicture', { rules: [{ required: true, message: 'banner图片不能为空!' }] }]"
          >
            <img class="bannerImg" v-if="bannerPicture" :src="bannerPicture" alt="banner" />
            <div v-else>
              <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="banner名称">
          <a-input v-decorator="['bannerName', { rules: [{ required: true, message: 'banner名称不能为空!' }] }]" />
        </a-form-item>
        <a-form-item label="客服端类型">
          <a-select
            placeholder="请选择客服端类型"
            v-decorator="[
              'clientType',
              { rules: [{ required: true, message: '请选择客服端类型,客服端类型不能为空！' }] },
            ]"
          >
            <a-select-option :value="1">商户</a-select-option>
            <a-select-option :value="2">消费者</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="banner类型">
          <a-select
            placeholder="请选择banner类型"
            v-decorator="[
              'bannerType',
              { rules: [{ required: true, message: '请选择banner类型,banner类型不能为空！' }] },
            ]"
            @change="_bannerTypeChange"
          >
            <a-select-option value="IMG">IMG</a-select-option>
            <a-select-option value="H5">H5</a-select-option>
            <a-select-option value="NOTICE">NOTICE</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="targetObj" v-show="bannerType">
          <a-input
            placeholder="请输入图片URL地址"
            v-decorator="['targetObj', { rules: [{ required: true, message: 'URL地址不能为空!' }] }]"
            v-if="bannerType === 'IMG'"
          />
          <a-input
            placeholder="请输入URL地址"
            v-decorator="['targetObj', { rules: [{ required: true, message: 'URL地址不能为空!' }] }]"
            v-else-if="bannerType === 'H5'"
          />
          <a-input
            placeholder="请输入通知ID"
            v-decorator="['targetObj', { rules: [{ required: true, message: '通知ID不能为空!' }] }]"
            v-else-if="bannerType === 'NOTICE'"
          />
        </a-form-item>
        <a-form-item label="开始时间">
          <a-date-picker
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            v-decorator="['expiryStartTime', { rules: [{ required: true, message: '开始时间不能为空！' }] }]"
          />
        </a-form-item>
        <a-form-item label="截止时间">
          <a-date-picker
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            v-decorator="['expiryEndTime', { rules: [{ required: true, message: '截止时间不能为空！' }] }]"
          />
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            placeholder="请选择状态"
            v-decorator="['status', { rules: [{ required: true, message: '请选择状态,状态不能为空！' }] }]"
          >
            <a-select-option :value="1">启用</a-select-option>
            <a-select-option :value="2">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="显示顺序">
          <a-input v-decorator="['seq', { rules: [{ required: true, message: '显示顺序不能为空！' }] }]" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { uploadFile } from '@/api/common'
// 表单字段
const fields = [
  'bannerId',
  'bannerPicture',
  'bannerName',
  'clientType',
  'bannerType',
  'targetObj',
  'expiryStartTime',
  'expiryEndTime',
  'status',
  'seq'
]

function getBase64 (img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}

export default {
  props: {
    title: {
      type: String,
      required: true
    },
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      uploadLoading: false,
      bannerPicture: '',
      bannerType: '',
      form: this.$form.createForm(this)
    }
  },
  methods: {
    /**
     * bannerType切换
     */
    _bannerTypeChange (bannerType) {
      this.bannerType = bannerType
    },
    /**
     * 提交表单
     */
    _submit: function () {
      this.$emit('ok')
    },
    /**
     * 取消
     */
    _cancel: function () {
      this.$emit('cancel')
    },
    handleChange (info) {
      if (info.file.status === 'uploading') {
        this.uploadLoading = true
        return
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, (bannerPicture) => {
          this.bannerPicture = bannerPicture
          this.uploadLoading = false
        })
      }
    },
    beforeUpload (file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJpgOrPng && isLt2M
    },
    customRequest (options) {
      const params = new FormData()
      this.uploadLoading = true
      params.append('file', options.file)
      params.append('uploadType', 'banner')
      uploadFile(params).then((res) => {
        this.bannerPicture = res.url
        this.form.setFieldsValue({
          bannerPicture: res.url
        })
      }).catch((e) => {})
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach((v) => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.bannerPicture = this.model?.bannerPicture ? this.model.bannerPicture : ''
      this.bannerType = this.model?.bannerType ? this.model.bannerType : ''
      if (this.model) {
        this.form.setFieldsValue(pick(this.model, fields))
        this.$nextTick(() => {
          this.form.setFieldsValue({
            targetObj: this.model.targetObj
          })
        })
      }
    })
  },
  mounted () {}
}
</script>
<style lang="less" scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.bannerImg {
  width: 100%;
  height: 100%;
}
</style>
